package xdu.lz.stage4_atomic.chapter3_atomicReference;

import java.util.concurrent.atomic.AtomicReference;

/**
 如果使用原子性对象引用，在多线程情况下进行对象的更新可以确保一致性。例如：
 Atomic Person is [name: Tom, age: 18]
 Thread1 Atomic References [name: Tom1, age: 19]
 Thread2 Atomic References [name: Tom2, age: 21]
 Now Atomic Person is [name: Tom2, age: 21]
 */
public class Test2 {
    // 普通引用
    private static Person person;
    // 原子性引用
    private static AtomicReference<Person> personReference;

    public static void main(String[] args) throws InterruptedException {
        person = new Person("Tom", 18);
        personReference = new AtomicReference<Person>(person);

        System.out.println("Atomic Person is " + personReference.get().toString());

        Thread t1 = new Thread(new Task1());
        Thread t2 = new Thread(new Task2());

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println("Now Atomic Person is " + personReference.get().toString());
    }

    static class Task1 implements Runnable {
        public void run() {
            personReference.getAndSet(new Person("Tom1", personReference.get().getAge() + 1));
            System.out.println("Thread1 Atomic References "
                    + personReference.get().toString());
        }
    }

    static class Task2 implements Runnable {
        public void run() {
            personReference.getAndSet(new Person("Tom2", personReference.get().getAge() + 2));
            System.out.println("Thread2 Atomic References "
                    + personReference.get().toString());
        }
    }
}
